package com.handpay.zztong.hp.accountcenter.activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.framework.HttpSFTConnector;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.accountcenter.widget.ConfirmPhotoView;
import com.handpay.zztong.hp.accountcenter.widget.ConfirmPhotoView.UploadClickListener;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.permission.PermissionRequestCode;
import com.handpay.zztong.hp.protocol.UploadProtocolConstant;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.util.List;

/**
 * 拍摄照片
 */
public class BaseInfoPrepareImageActivity extends ZZTongActivity {
    private ConfirmPhotoView mFrontCard;
    private ConfirmPhotoView mBackCard;
    private ConfirmPhotoView mCardInHand;
    private ConfirmPhotoView mShopPic;
    private ConfirmPhotoView mBusinessLicence;
    public static int TAKE_PICTURE = 1;
    public static int TAKE_PICTURE_FRONT = TAKE_PICTURE + 1;
    public static int TAKE_PICTURE_BLACK = TAKE_PICTURE + 2;
    public static int TAKE_PICTURE_IN_HAND = TAKE_PICTURE + 3;
    public static int TAKE_PICTURE_SHOP = TAKE_PICTURE + 4;
    public static int TAKE_PICTURE_BUS_LICENSE = TAKE_PICTURE + 5;
    private Uri mPicUri;
    private File mPic;
    @Override
    protected boolean isShownTabs() {
        return false;
    }

    private static boolean convertStatusToBoolean(String status) {
        // 1表示是审核通过。
        return "1".equals(status);
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.prepare_image_title), true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        HPLog.i("time", "onCreate" + SystemClock.elapsedRealtime());
        this.setContentView(R.layout.activity_base_info_prepare_image);
        super.onCreate(savedInstanceState);
        //如果没有相机权限则去获取相机权限
        if (!AndPermission.hasPermission(this, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            AndPermission.with(this).
                    requestCode(PermissionRequestCode.REQUEST_CODE_CAMERA_STORAGE).
                    permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).
                    rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            AndPermission.rationaleDialog(BaseInfoPrepareImageActivity.this, rationale).
                                    show();
                        }
                    }).send();
        }
        mFrontCard = (ConfirmPhotoView) this.findViewById(R.id.c_id_front_photo);
        mBackCard = (ConfirmPhotoView) this.findViewById(R.id.c_id_back_photo);
        mCardInHand = (ConfirmPhotoView) this.findViewById(R.id.c_person_with_id);
        mShopPic = (ConfirmPhotoView) this.findViewById(R.id.c_shop_pic);
        mBusinessLicence = (ConfirmPhotoView) this.findViewById(R.id.c_business_licence);
        mBusinessLicence.setOptional(true);
        String frontUri = null;
        boolean frontStatus = false;
        String backUri = null;
        boolean backStatus = false;
        String cardInHandUri = null;
        boolean inHandStatus = false;
        String shopUri = null;
        boolean shopStatus = false;
        String businessLicenseUri = null;
        boolean businessStatus = false;
        // 如果是第一次上传。隐藏warning
        if (AccountUtils.AccountStatus.FAIL == AccountUtils.getAccountStatus(this)) {
            this.findViewById(R.id.reupload_warning).setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.reupload_warning_content)).setText(AccountUtils.getAccountFailDes(this));
            Intent i = getIntent();
            frontUri = i.getStringExtra(UploadProtocolConstant.KEY_FRONTCCPIC);
            frontStatus = convertStatusToBoolean(i.getStringExtra(UploadProtocolConstant.KEY_FRONTCCPICSTATUS));
            backUri = i.getStringExtra(UploadProtocolConstant.KEY_BACKCCPIC);
            backStatus = convertStatusToBoolean(i.getStringExtra(UploadProtocolConstant.KEY_BACKCCPICSTATUS));
            cardInHandUri = i.getStringExtra(UploadProtocolConstant.KEY_HOLDPIC);
            inHandStatus = convertStatusToBoolean(i.getStringExtra(UploadProtocolConstant.KEY_HOLDPICSTATUS));
            shopUri = i.getStringExtra(UploadProtocolConstant.KEY_COMPANYPIC);
            shopStatus = convertStatusToBoolean(i.getStringExtra(UploadProtocolConstant.KEY_COMPANYPICSTATUS));
            businessLicenseUri = i.getStringExtra(UploadProtocolConstant.KEY_BLICENSEPIC);
            businessStatus = convertStatusToBoolean(i.getStringExtra(UploadProtocolConstant.KEY_BLICENSEPICSTATUS));
        } else {
            findViewById(R.id.reupload_warning).setVisibility(View.GONE);
        }
        HPLog.i("", "start time:" + SystemClock.elapsedRealtime());
        mFrontCard.init(getString(R.string.ID_card_photo), R.drawable.idcardphoto, R.drawable.idcardphoto_large, frontUri, frontStatus, mUploadClickListener);
        mBackCard.init(getString(R.string.ID_card_back_photo), R.drawable.idcardbackphoto, R.drawable.idcardbackphoto_large, backUri, backStatus, mUploadClickListener);
        mCardInHand.init(getString(R.string.ID_person_with_card), R.drawable.withidcardphoto, R.drawable.withidcardphoto_large, cardInHandUri, inHandStatus, mUploadClickListener);
        mShopPic.init(getString(R.string.shop_pic), R.drawable.placephoto, R.drawable.shoppic_large, shopUri, shopStatus, mUploadClickListener);
        mBusinessLicence.init(getString(R.string.business_license), R.drawable.placephoto, R.drawable.business_license_large, businessLicenseUri, businessStatus, mUploadClickListener);
        HPLog.i("", "end time:" + SystemClock.elapsedRealtime());
        findViewById(R.id.nextButton).setOnClickListener(CommonUtils.createNoQuickResponseViewListener(ZZTConstant.NO_RESPONSE_CLICK_TIME, new OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = "";
                String frontUri = mFrontCard.getPicUri();
                String backUri = mBackCard.getPicUri();
                String inHandUri = mCardInHand.getPicUri();
                String shopPicUri = mShopPic.getPicUri();
                String busLic = mBusinessLicence.getPicUri();
                if (TextUtils.isEmpty(frontUri) || !mFrontCard.isLoadSuccess) {
                    message = getString(R.string.tv_please_takephoto_front);
                } else if (TextUtils.isEmpty(backUri) || !mBackCard.isLoadSuccess) {
                    message = getString(R.string.tv_please_takephoto_back);
                } else if (TextUtils.isEmpty(inHandUri) || !mCardInHand.isLoadSuccess) {
                    message = getString(R.string.tv_please_takephoto_hold);
                } else if (TextUtils.isEmpty(shopPicUri) || !mShopPic.isLoadSuccess) {
                    message = getString(R.string.tv_please_takephoto_shop_pic);
                }
                if (!TextUtils.isEmpty(message)) {
                    // alert use
                    BaseInfoPrepareImageActivity.this.showAlertDialog(BaseInfoPrepareImageActivity.this, getString(R.string.tip), message, true);
                } else {
                    Intent t = getIntent();
                    t.putExtra(UploadProtocolConstant.TYPE.FRONT.toString(), frontUri);
                    t.putExtra(UploadProtocolConstant.TYPE.BACK.toString(), backUri);
                    t.putExtra(UploadProtocolConstant.TYPE.INHAND.toString(), inHandUri);
                    t.putExtra(UploadProtocolConstant.TYPE.SHOPPIC.toString(), shopPicUri);
                    t.putExtra(UploadProtocolConstant.TYPE.BUS_LIC.toString(), busLic);
                    t.setClass(BaseInfoPrepareImageActivity.this, BaseInfoConfirmUploadActivity.class);
                    BaseInfoPrepareImageActivity.this.startActivity(t);
                }
            }
        }));
    }

    private UploadClickListener mUploadClickListener = new UploadClickListener() {
        @Override
        public void onUploadClickListener(ConfirmPhotoView view) {
            if (!AndPermission.hasPermission(BaseInfoPrepareImageActivity.this, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                AndPermission.with(BaseInfoPrepareImageActivity.this).
                        requestCode(PermissionRequestCode.REQUEST_CODE_CAMERA_STORAGE).
                        permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).
                        rationale(new RationaleListener() {
                            @Override
                            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                AndPermission.rationaleDialog(BaseInfoPrepareImageActivity.this, rationale).
                                        show();
                            }
                        }).send();
                return;
            }
            mPicUri = CommonUtils.randomUriWithFilePrivider(BaseInfoPrepareImageActivity.this,CommonUtils.getAccessDir());
            Intent intent = new Intent();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
            }
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicUri);//将拍取的照片保存到指定URI
            int requestCode = TAKE_PICTURE;
            if (mFrontCard == view) {
                requestCode = TAKE_PICTURE_FRONT;
            } else if (mBackCard == view) {
                requestCode = TAKE_PICTURE_BLACK;
            } else if (mCardInHand == view) {
                requestCode = TAKE_PICTURE_IN_HAND;
            } else if (mShopPic == view) {
                requestCode = TAKE_PICTURE_SHOP;
            } else if (mBusinessLicence == view) {
                requestCode = TAKE_PICTURE_BUS_LICENSE;
            }
            startActivityForResult(intent, requestCode);
        }
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Activity.RESULT_OK == resultCode) {
            ConfirmPhotoView photo = null;
            if (TAKE_PICTURE_FRONT == requestCode) {
                photo = mFrontCard;
            } else if (TAKE_PICTURE_BLACK == requestCode) {
                photo = mBackCard;
            } else if (TAKE_PICTURE_IN_HAND == requestCode) {
                photo = mCardInHand;
            } else if (TAKE_PICTURE_SHOP == requestCode) {
                photo = mShopPic;
            } else if (TAKE_PICTURE_BUS_LICENSE == requestCode) {
                photo = mBusinessLicence;
            }
//            String path = data.getStringExtra(CameraCardActivity.RESULT_PATH);
            if (mPicUri != null) {
                String uri = mPicUri.toString();
                photo.setPic(uri);

            }
            mPicUri = null;
        } else if (requestCode == PermissionRequestCode.REQUEST_CODE_CAMERA_STORAGE) {
            Toast.makeText(this, R.string.message_camera_storage_failed, Toast.LENGTH_SHORT).show();
            if (!AndPermission.hasPermission(this, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                AndPermission.with(this).
                        requestCode(PermissionRequestCode.REQUEST_CODE_CAMERA_STORAGE).
                        permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).
                        rationale(new RationaleListener() {
                            @Override
                            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                AndPermission.rationaleDialog(BaseInfoPrepareImageActivity.this, rationale).
                                        show();
                            }
                        }).send();
            }
        }
        // 控制程序调用相机的时候，不去发版本检测协议。
        ZZTConfig.isActive = false;
        HPLog.e("shuai", "ZZTConfig.isActive: " + ZZTConfig.isActive);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //由于内存不足 判断session是否被回收
        if (!HttpSFTConnector.hasSessionID()) {
            //内存不足情况无法进行罗就流程
            showAlertDialog(this, getString(R.string.tip), getString(R.string.low_merry_warring), false, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
        }
    }

    @Override
    public void onSucceed(int requestCode, List<String> grantPermissions) {
        if (requestCode == PermissionRequestCode.REQUEST_CODE_CAMERA_STORAGE) {
            Toast.makeText(BaseInfoPrepareImageActivity.this, R.string.message_camera_storage_succesed, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void goBack() {
        super.goBack();
    }
}
